<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/12/30
 * Time: 10:22
 */

namespace common\components\ActionsComponents;


use yii\base\Action;
use yii\base\Exception;

class CommonAction extends Action
{
    public $model;

    public $condition = [];

    public $scenarios = 'default';

    public $url;

    public $params = [];

    public $data = [];

    public $callback;

    public $before;

    /**
     * 是否渲染json
     * @var bool
     */
    public $isRenderJSON = true;

    /**
     * 如果为true则表示获取所有请求
     * false则只获取post
     * @var bool
     */
    public $isRequest = false;

    /**
     * 所有请求参数
     * @var
     */
    protected $_request;

    public $_pk = 'id';

    public $isPushLocal = false;

    /**
     * 处理闭包
     * CommonAction constructor.
     * @param string $id
     * @param \yii\base\Controller $controller
     * @param array $config
     * @throws Exception
     */
    public function __construct($id, $controller, array $config = [])
    {
        parent::__construct($id, $controller, $config);

        if ( $this->condition instanceof \Closure ) {
            $condition = $this->condition;
            $this->condition = $condition();

            if ( !is_array($this->condition) && !is_string($this->condition) )  {
                throw new Exception('condition 参数必须是一个数组或者字符串');
            }
        }

        if ( $this->isRequest ) {
            $this->_request = array_merge(\Yii::$app->getRequest()->getBodyParams(), $controller->get(), (array)$this->params);
        } else  {
            $this->_request = array_merge(\Yii::$app->request->isPost ? $controller->post() : $controller->get(), (array)$this->params);
        }

        if ( $this->url ) {
            $this->data[$controller::RESPONSE_DATA_URL] = $this->url;
        }
    }

}